package com.wiz.weixin.controllor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.manager.WxAccessManager;

/**
 * 会员
 * @author xxy
 */
@Controller
@RequestMapping("/test")
public class TestControllor {
	
	@Resource
	private TencentManager tencentManager;

	/** 授权 */
	@RequestMapping(value = "/set", method = RequestMethod.POST)
	@ResponseBody
	public String prepay(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "ticket", required = true) String ticket,
			HttpSession session, Model model) throws Exception {
		WxAccessManager.setTencent_wx_token(token);
		WxAccessManager.setTencent_wx_ticket(ticket);
		return "success";
	}
	
	/** 授权 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String test(HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (!agent.contains("micromessenger")) {
			model.addAttribute("msg", "请使用微信自带的浏览注册！");
			return "/error";
		}
		String code = request.getParameter("code");
		String openId = tencentManager.getOpenId(code);
//		String openId = "ovNRGs45WudglvjfjUth3W57tJOU";
		if (StringUtils.isBlank(openId)) {
			model.addAttribute("msg", "无法取得微信用户编码");
			return "/error";
		}
		session.setAttribute("openid", openId);
		return "/test";
	}
}
